package juego;

import java.lang.Math;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Coordenada implements Persistible {
	
	//atributos de instancia
	private int x;
	private int y;

	//metodos
	
	public Coordenada(int coordenadaX, int coordenadaY) {
		this.x = coordenadaX;
		this.y = coordenadaY;
	}
	
	public int obtenerCoordenadaX() {
		return x;
	};
	
	public int obtenerCoordenadaY() {
		return y;
	};
	
	public void cambiarCoordenadaX(int coordenadaX) {
		this.x = coordenadaX;
	};
	
	public void cambiarCoordenadaY(int coordenadaY) {
		this.y = coordenadaY;
	};

	public void moverEnX(int horizontal) {
		this.x += horizontal;
	};
	
	public void moverEnY(int vertical) {
		this.y += vertical;
	};
	
	public void moverEnXY(int horizontal, int vertical) {
		this.x += horizontal;
		this.y += vertical;
	}


	public int distancia(Coordenada punto) {
		int distanciaEnX = (punto.obtenerCoordenadaX() - this.x);
		int distanciaEnY = (punto.obtenerCoordenadaY() - this.y);
		Coordenada vector = new Coordenada(distanciaEnX,distanciaEnY);
		int modulo = (int) vector.getModulo();
		return modulo;
	}
	
	public double getModulo(){
		double suma = (x * x) + (y * y);
		double modulo = Math.sqrt(suma);
		return modulo;
	}
	

	public void normalizar(){
		double modulo = this.getModulo();
		double temporalX = x/modulo;
		double temporalY = y/modulo;
		x = (int) Math.round(temporalX);
		y = (int) Math.round(temporalY);
	}
	
	public Element getElement(Document doc) {
		Element coordenada = doc.createElement("Coordenada");

		Integer valorX = new Integer(this.x);
		Element x = doc.createElement("X");
		coordenada.appendChild(x);
		x.setTextContent(valorX.toString());
		
		Integer valorY = new Integer(this.y);
		Element y = doc.createElement("Y");
		coordenada.appendChild(y);
		y.setTextContent(valorY.toString());

		return coordenada;
	}
	
	public static Coordenada fromElement(Element element) {
		int valorX = 0;
		int valorY = 0;
		
		NodeList childs = element.getChildNodes();
		for (int i = 0; i < childs.getLength(); i++) {
			Node child = childs.item(i);
			if (child.getNodeName().equals("X")) {
				valorX = Integer.parseInt(child.getTextContent());
			} else if (child.getNodeName().equals("Y")) {
				valorY = Integer.parseInt(child.getTextContent());
			}
		}
		
		Coordenada coordenada = new Coordenada(valorX,valorY);
		
		return coordenada;
	}
		
         
	
}
